const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require("koa2-cors");
const {koaBody }= require('koa-body');    //引入koa-body

const login = require('./routes/login')
const adminstudent = require('./routes/adminstudent')
const adminteacher = require('./routes/adminteacher')
const admincourse = require('./routes/admincourse')
const studentcourse = require('./routes/studentcourse')
const teachercourse = require('./routes/teachercourse')
const adminhome = require('./routes/adminhome')
const score = require('./routes/score')
const homework = require('./routes/homework')
const path = require('path');
const serve = require('koa-static');
// error handler
onerror(app)

// 设置静态文件目录
app.use(serve(path.join(__dirname, './routes/uploads')));


app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: './routes/uploads/',
    keepExtensions: true,
    maxFileSize: 200 * 1024 * 1024 // 限制文件大小为200MB 
  }
}));
// middlewares
app.use(cors());
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes

app.use(studentcourse.routes(),studentcourse.allowedMethods())
app.use(login.routes(),login.allowedMethods())
app.use(adminstudent.routes(),adminstudent.allowedMethods())
app.use(adminteacher.routes(),adminteacher.allowedMethods())
app.use(admincourse.routes(),admincourse.allowedMethods())
app.use(teachercourse.routes(),teachercourse.allowedMethods())
app.use(adminhome.routes(),adminhome.allowedMethods())
app.use(score.routes(),score.allowedMethods())
app.use(homework.routes(),homework.allowedMethods())
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

app.listen(8000,()=>{
  console.log("服务已启动，端口8000")
})

module.exports = app
